package Lab2;

import java.util.ArrayList;

public class ObjectList<E> {
	private static final int MAX_ITEMS = 20;

	private E[] allItems;
	private int nextEmptySlot;
	
	public ObjectList() {
		allItems = (E[]) new Object[MAX_ITEMS];
		nextEmptySlot = 0;
	}
	
	public ObjectList(ObjectList<E> otherList) {
		allItems = (E[]) new Object[otherList.allItems.length];

		for(int i=0;i<otherList.nextEmptySlot;i++) {
			allItems[i] = otherList.allItems[i];
		}
		
		nextEmptySlot = otherList.nextEmptySlot;
	}
	
	public void add(E what) {
		if (nextEmptySlot == allItems.length) {
			grow();
		}

		allItems[nextEmptySlot] = what;
		nextEmptySlot++;
	}

	private void grow() {
		E[] newItems = (E[]) new Object[allItems.length * 2];

		for (int copyIndex = 0; copyIndex < allItems.length; copyIndex++) {
			newItems[copyIndex] = allItems[copyIndex];
		}

	}

	public void insertAtPosition(E what, int insertPosition) {
		int firstPosToMove = insertPosition;
		int lastPosToMove = nextEmptySlot;
		
		for (int movePos = lastPosToMove; movePos >= firstPosToMove; movePos--) {
			allItems[movePos + 1] = allItems[movePos];
		}
		
		allItems[firstPosToMove] = what;
		nextEmptySlot++;
	}
	
	// contains, a simple boolean check that loops through our list and
	// checks each cell for anything that 'looks like' our given parameter object.
	// 'looks like' means contains similar data to given object, though the given object
	// may not be the actual variable from another list, but rather a brand new object
	// created for the search.
	public boolean contains(E looksLike) {
		
		for(int i=0;i<nextEmptySlot;i++) {
			if (allItems[i].equals(looksLike)) {
				return true;
			}
		}
		
		return false;
	}
	
	// remove, loops through the list, starting at the position of the cell we want removed,
	// and begins shifting data up until it hits nextEmptySlot. We then decrement nextEmptySpot.
	public void remove(int removePosition) {
		int firstPositionToMove = removePosition + 1;
		int lastPositionToMove = nextEmptySlot - 1;

		for (int copyPosition = firstPositionToMove; copyPosition <= lastPositionToMove; copyPosition++) {
			allItems[copyPosition - 1] = allItems[copyPosition];
		}
		
		nextEmptySlot--;
	}

	// getPosition, simply returns the cell position of our parameter object,
	// or -1 if it is not in the list.
	public E getPosition(int position) {
		return allItems[position];
	}

	// size, returns nextEmptySlot.
	public int size() {
		return nextEmptySlot;
	}

	// toString, a debug function we use to describe an entire list of objects,
	// printing out all their data to check if objects are constructed correctly.
	public String toString() {
		String theMembers = "";
		for (int memberNumber = 0; memberNumber < nextEmptySlot; memberNumber++) {
			theMembers = theMembers + " [ " + allItems[memberNumber] + " ] ";
		}

		return theMembers;
	}
}